// 用户收益模型 - 根据实际API数据更新
import 'dart:ui';

import 'package:bit_fury/controller/invite_controller.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class UserEarningsModel {
  final int id;
  final int type; // 0: Mining Contracts, 1: Referral Reward
  final String title;
  final String income; // 使用字符串保持精度
  final int timestamp;
  final DateTime dateTime;

  UserEarningsModel({
    required this.id,
    required this.type,
    required this.title,
    required this.income,
    required this.timestamp,
    required this.dateTime,
  });

  factory UserEarningsModel.fromJson(Map<String, dynamic> json) {
    final timestamp = json['timestamp'] ?? 0;
    return UserEarningsModel(
      id: json['id'] ?? 0,
      type: json['type'] ?? 0,
      title: json['title'] ?? '',
      income: json['income'] ?? '0',
      timestamp: timestamp,
      dateTime: DateTime.fromMillisecondsSinceEpoch(timestamp * 1000),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'type': type,
      'title': title,
      'income': income,
      'timestamp': timestamp,
    };
  }

  // 获取类型显示文本
  String get typeText {
    switch (type) {
      case 0:
        return 'mining_contract'.tr;
      case 1:
        return 'referral_reward'.tr;
      default:
        return 'other'.tr;
    }
  }

  // 获取收益金额（转换为double）
  double get incomeAmount {
    return double.tryParse(income) ?? 0.0;
  }

  // 格式化日期
  String get formattedDate {
    return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')}';
  }

  // 格式化时间
  String get formattedTime {
    return '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
  }
}

// 提现记录模型 - 根据实际API数据更新
class WithdrawRecordModel {
  final String title; // 币种名称，如 "BTC"
  final String receivedAmount; // 到账金额
  final int createAt; // 创建时间戳
  final int status; // 状态：1-处理中, 2-已完成, 3-失败
  final String remark; // 备注
  final DateTime dateTime;

  WithdrawRecordModel({
    required this.title,
    required this.receivedAmount,
    required this.createAt,
    required this.status,
    required this.remark,
    required this.dateTime,
  });

  factory WithdrawRecordModel.fromJson(Map<String, dynamic> json) {
    final createAt = json['create_at'] ?? 0;
    return WithdrawRecordModel(
      title: json['title'] ?? '',
      receivedAmount: json['received_amount'] ?? '0',
      createAt: createAt,
      status: json['status'] ?? 0,
      remark: json['remark'] ?? '',
      dateTime: DateTime.fromMillisecondsSinceEpoch(createAt * 1000),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'title': title,
      'received_amount': receivedAmount,
      'create_at': createAt,
      'status': status,
      'remark': remark,
    };
  }

  // 获取状态显示文本
  String get statusText {
    switch (status) {
      case 1:
        return 'processing'.tr;
      case 2:
        return 'completed'.tr;
      case 3:
        return 'failed'.tr;
      default:
        return 'failed';
    }
  }

  // 获取状态颜色
  Color get statusColor {
    switch (status) {
      case 1:
        return Colors.orange;
      case 2:
        return Colors.green;
      case 3:
        return Colors.red;
      default:
        return Colors.grey;
    }
  }

  // 获取到账金额（转换为double）
  double get receivedAmountValue {
    return double.tryParse(receivedAmount) ?? 0.0;
  }

  // 格式化日期
  String get formattedDate {
    return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')}';
  }

  // 格式化时间
  String get formattedTime {
    return '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
  }
}

// 网络配置模型 - 根据提现页面数据API
class NetworkConfigModel {
  final int id;
  final String title;
  final String networkFee;
  final String minimumAmount;
  final int status;

  NetworkConfigModel({
    required this.id,
    required this.title,
    required this.networkFee,
    required this.minimumAmount,
    required this.status,
  });

  factory NetworkConfigModel.fromJson(Map<String, dynamic> json) {
    return NetworkConfigModel(
      id: json['id'] ?? 0,
      title: json['title'] ?? '',
      networkFee: json['network_fee'] ?? '0',
      minimumAmount: json['minimum_amount'] ?? '0',
      status: json['status'] ?? 0,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
      'network_fee': networkFee,
      'minimum_amount': minimumAmount,
      'status': status,
    };
  }

  // 获取网络费用（转换为double）
  double get networkFeeValue {
    return double.tryParse(networkFee) ?? 0.0;
  }

  // 获取最小金额（转换为double）
  double get minimumAmountValue {
    return double.tryParse(minimumAmount) ?? 0.0;
  }

  // 是否可用
  bool get isAvailable {
    return status == 1;
  }
}

// 用户收益响应模型
class UserEarningsResponse {
  final String btcNum;
  final List<UserEarningsModel> list;

  UserEarningsResponse({
    required this.btcNum,
    required this.list,
  });

  factory UserEarningsResponse.fromJson(Map<String, dynamic> json) {
    return UserEarningsResponse(
      btcNum: json['btc_num'] ?? '0',
      list: (json['list'] as List<dynamic>? ?? [])
          .map((item) => UserEarningsModel.fromJson(item))
          .toList(),
    );
  }

  // 获取BTC总数（转换为double）
  String get btcNumValue {
    return btcNum;
  }
}

// 提现记录响应模型
class WithdrawRecordsResponse {
  final List<WithdrawRecordModel> list;

  WithdrawRecordsResponse({
    required this.list,
  });

  factory WithdrawRecordsResponse.fromJson(Map<String, dynamic> json) {
    return WithdrawRecordsResponse(
      list: (json['list'] as List<dynamic>? ?? [])
          .map((item) => WithdrawRecordModel.fromJson(item))
          .toList(),
    );
  }
}

// 提现页面数据响应模型
class WithdrawPageDataResponse {
  final List<NetworkConfigModel> network;
  final String amount;

  WithdrawPageDataResponse({
    required this.network,
    required this.amount,
  });

  factory WithdrawPageDataResponse.fromJson(Map<String, dynamic> json) {
    return WithdrawPageDataResponse(
      network: (json['network'] as List<dynamic>? ?? [])
          .map((item) => NetworkConfigModel.fromJson(item))
          .toList(),
      amount: json['amount'] ?? '0',
    );
  }

  // 获取可用余额（转换为double）
  double get amountValue {
    return double.tryParse(amount) ?? 0.0;
  }
}

// 统一记录模型 - 用于在近期记录中同时显示收益和提现记录
class RecentRecordModel {
  final String id;
  final String type; // 'earning' 或 'withdraw'
   String title;
  final String amount;
  final DateTime dateTime;
  final String status;
  final String? remark;
  final int? originalType; // 对于收益记录，保存原始type值
  final int? withdrawStatus; // 对于提现记录，保存原始status值

  RecentRecordModel({
    required this.id,
    required this.type,
    required this.title,
    required this.amount,
    required this.dateTime,
    required this.status,
    this.remark,
    this.originalType,
    this.withdrawStatus,
  });

  // 从收益记录创建
  factory RecentRecordModel.fromEarning(UserEarningsModel earning) {
    return RecentRecordModel(
      id: earning.id.toString(),
      type: 'earning',
      title: earning.title,
      amount: earning.income,
      dateTime: earning.dateTime,
      status: '',
      originalType: earning.type,
    );
  }

  // 从提现记录创建
  factory RecentRecordModel.fromWithdraw(WithdrawRecordModel withdraw) {
    return RecentRecordModel(
      id: withdraw.createAt.toString(),
      type: 'withdraw',
      title: 'Withdraw${withdraw.title}',
      amount: withdraw.receivedAmount,
      dateTime: withdraw.dateTime,
      status: "",
      remark: withdraw.remark.isNotEmpty ? withdraw.remark : null,
      withdrawStatus: withdraw.status,
    );
  }

  // 获取金额（转换为double）
  double get amountValue {
    return double.tryParse(amount) ?? 0.0;
  }

  // 获取显示的金额（收益为正，提现为负）
  double get displayAmount {
    final value = amountValue;
    return type == 'withdraw' ? -value : value;
  }

  // 获取状态颜色
  Color get statusColor {
    if (type == 'earning') {
      return Colors.green;
    } else {
      switch (withdrawStatus) {
        case 1:
          return Colors.green;
        case 2:
          return Colors.red;
        case 3:
          return Colors.orange;
        default:
          return Colors.orange;
      }
    }
  }


   String get statusTitle {
       switch (withdrawStatus) {
        case 1:
          return "Withdrawal Successful";
        case 2:
          return "Withdrawal Failed";
        case 3:
          return "Withdrawal Pending";
        default:
          return "Withdrawal Pending";
      }
  }



  // 格式化日期
  String get formattedDate {
    return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')}';
  }

  // 格式化时间
  String get formattedTime {
    return '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
  }

  // 获取类型图标
  IconData get typeIcon {
    if (type == 'earning') {
      return originalType == 0 ? Icons.memory : Icons.people;
    } else {
      return Icons.arrow_upward;
    }
  }
}